package it.polito.let.jhp.form;

import it.polito.let.jhp.types.EnumType;
import it.polito.let.jhp.types.TypeList;

import java.util.Map;

public class FormTag {

	private static final String ClosedTagO = "</";

	private static final String OpenTagO = "<";

	private static final String TagC = ">";

	private String name;

	private Map<String,String> attrMap;

	private FormTagClass _class;

	private boolean openTag;

	public FormTag (String name) {
		this(name,null);
	}

	public FormTag (String name, Map<String,String> attrMap) {
		openTag = true;
		this.attrMap = attrMap;
		this.name = name;
		if(name.equalsIgnoreCase("input")) {
			_class = FormTagClass.INPUT;
		} else if (name.equalsIgnoreCase("textarea")) {
			_class = FormTagClass.TEXTAREA;
		} else {
			_class = FormTagClass.OTHER;
		}
	}

	public boolean isOpenTag () {
		return openTag;
	}

	public void setOpenTag () {
		openTag = true;
	}

	public void setCloseTag () {
		openTag = false;
	}

	public void setAttrMap (Map<String,String> attrMap) {
		this.attrMap = attrMap;
	}

	public FormTagClass getTagClass () {
		return _class;
	}

	public enum FormTagClass {
		INPUT,
		TEXTAREA,
		OTHER;
	}

	public String getNameAttr() {
		if (attrMap==null || !attrMap.containsKey("name"))
			return null;
		return attrMap.get("name");
	}

	public String getTypeAttr() {
		if (attrMap==null || !attrMap.containsKey("type"))
			return null;
		return attrMap.get("type");
	}

	public String toString(TypeList type) {
		if(!type.isList())
		{
			switch (type.getType().getOriginalType()) {
			case ENUM:
				StringBuffer buf = new StringBuffer();
				EnumType et = (EnumType) type.getType();
				switch (et.getRender()) {
				case radio:
				case checkbox:
					attrMap.put("type",""+et.getRender().toString()+"");
					for (Object k:et.getEnumValues().keySet()) {
						Object v = et.getEnumValues().get(k);
						attrMap.put("value", ""+k.toString()+"");
						buf.append(toString()+v.toString()+"\r\n");
					}
					return buf.toString();
				case select:
					name = "select";
					attrMap.remove("type");
					buf.append(toString()+"\r\n");
					for (Object k:et.getEnumValues().keySet()) {
						Object v = et.getEnumValues().get(k);
						buf.append("<option value=\""+k.toString()+"\">"+ v.toString() +"</option>\r\n");
					}
					buf.append("</select>\r\n");
					return buf.toString();
				}
			default:
				attrMap.put("type", "text");
			return toString();
			}
		}
		else
		{
			attrMap.put("type", "text");
			return toString();
		}
	}

	public String toString() {
		StringBuffer buf = new StringBuffer();
		buf.append(openTag ? OpenTagO : ClosedTagO);
		buf.append(name);
		if (attrMap != null) {
			for (String k:attrMap.keySet()) {
				buf.append(" "+k+"=\""+attrMap.get(k)+"\"");
			}
		}
		buf.append(TagC);
		return buf.toString();
	}


}
